﻿namespace LookupWithPicker
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint.WebControls;
    using System.Collections;
    using Microsoft.SharePoint;
    using System.Diagnostics;

    public class LookupWithPickerField : BaseFieldControl
    {
        private CustomLookupEntityEditor lookupEditor;

        private string lookupList;
        private bool allowMultipleValues;
        
        public string LookupList
        {
            get
            {
                return this.lookupList;
            }

            set
            {
                this.lookupList = value;
            }
        }

        public bool AllowMultipleValues
        {
            get
            {
                return this.allowMultipleValues;
            }

            set
            {
                this.allowMultipleValues = value;
            }
        }

        public override object Value
        {
            get
            {
                object res = null;
                this.EnsureChildControls();
                if (this.lookupEditor != null)
                {
                    ArrayList resolvedEntities = this.lookupEditor.ResolvedEntities;
                    if (this.allowMultipleValues)
                    {
                        string str = "";
                        if (resolvedEntities.Count > 0)
                        {
                            foreach (PickerEntity entity in resolvedEntities)
                            {
                                if (str.Length > 0)
                                {
                                    str += ";#";
                                }

                                str += entity.Key + ";#" + entity.Description;
                            }
                        }

                        if (!string.IsNullOrEmpty(str))
                        {
                            res = new SPFieldLookupValueCollection(str);
                        }
                        else
                        {
                            res = new SPFieldLookupValueCollection();
                        }
                    }
                    else
                    {
                        string str = "";
                        if (resolvedEntities.Count > 0)
                        {
                            PickerEntity entity = resolvedEntities[0] as PickerEntity;
                            str += entity.Key + ";#" + entity.Description;
                        }

                        if (!string.IsNullOrEmpty(str))
                        {
                            res = new SPFieldLookupValue(str);
                        }
                        else
                        {
                            res = new SPFieldLookupValue();
                        }
                    }
                }
                return res;
            }

            set
            {
                this.EnsureChildControls();
                this.SetFieldControlValue(value);
            }
        }

        public override void Validate()
        {
            if ((base.ControlMode != SPControlMode.Display) && base.IsValid)
            {
                base.Validate();
                if (base.Field.Required)
                {
                    if (this.allowMultipleValues)
                    {
                        if ((this.Value as SPFieldLookupValueCollection).Count == 0)
                        {
                            base.ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
                            base.IsValid = false;
                            return;
                        }
                    }
                    else
                    {
                        if ((this.Value as SPFieldLookupValue).LookupId <= 0)
                        {
                            base.ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
                            base.IsValid = false;
                            return;
                        }
                    }
                }
            }
            else
            {
                return;
            }
            /*
            if (((((base.List.BaseType == SPBaseType.DocumentLibrary) && (base.Field is SPFieldLookup)) && !(base.Field as SPFieldLookup).UnlimitedLengthInDocumentLibrary) && (this.Value != null)) && (this.Value.ToString().Length > 0xffL))
            {
                base.ErrorMessage = SPResource.GetString("InputLengthGreaterThanMaxLength", new object[] { 0xffL });
                base.IsValid = false;
            }
            */
        }

        protected override string DefaultTemplateName
        {
            get
            {
                return "LookupWithPickerField";
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                this.lookupEditor = (CustomLookupEntityEditor)this.TemplateContainer.FindControl("LookupWithPickerFld");
                if (this.lookupEditor != null)
                {
                    this.lookupEditor.CustomProperty = ((SPFieldLookupWithPicker)this.Field).LookupList + "#" + ((SPFieldLookupWithPicker)this.Field).LookupField + "#" + ((SPFieldLookupWithPicker)this.Field).LookupWebId.ToString();
                    this.lookupEditor.MultiSelect = this.AllowMultipleValues;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("CreateChildControls exception: " + ex.Message);
                Debug.WriteLine("CreateChildControls exception: " + ex.Message);
            }
        }

        private void SetFieldControlValue(object value)
        {
            if (this.lookupEditor != null)
            {
                this.lookupEditor.Entities.Clear();
                if (value is SPFieldLookupValueCollection)
                {
                    ArrayList list = new ArrayList();
                    SPFieldLookupValueCollection lookupValues = value as SPFieldLookupValueCollection;
                    foreach (SPFieldLookupValue lookupValue in lookupValues)
                    {
                        PickerEntity entity = this.lookupEditor.GetEntityById(lookupValue.LookupId);
                        if (entity != null)
                        {
                            list.Add(entity);
                        }
                    }

                    this.lookupEditor.UpdateEntities(list);
                }
                else
                {
                    if (value is SPFieldLookupValue)
                    {
                        SPFieldLookupValue lookupValue = value as SPFieldLookupValue;
                        PickerEntity entity = this.lookupEditor.GetEntityById(lookupValue.LookupId);
                        if (entity != null)
                        {
                            ArrayList list = new ArrayList();
                            list.Add(entity);
                            this.lookupEditor.UpdateEntities(list);
                        }
                    }
                }
            }
        }
    }
}
